﻿using System;
using System.Collections.Generic;
using System.Linq;
using QDT.Core.Members;

namespace QDT.Services.Members
{
    public partial class UserService
    {
        /// <summary>
        /// 创建用户绑定银行
        /// </summary>
        public UserBank CreateUserBank(int userId, int bankId, string bankCard, string bankZone, int regionLv1, int regionLv2,
                                       int regionLv3, int regionLv4)
        {
            var banks = DbProvider.D<UserBank>().Where(x => x.UserId == userId).ToList();
            if (banks.Count >= 3)
            {
                throw new ArgumentNullException("userId", "绑定银行卡数超过限制。");
            }
            if (banks.Any(x=>x.BankCard == bankCard))
            {
                throw new ArgumentNullException("bankCard", "该卡号已绑定不能重复绑定！");
            }
            var defaultbank = banks.FirstOrDefault(x => x.IsDefault);
            if (defaultbank != null) defaultbank.IsDefault = false;

            var bank = new UserBank(userId, bankId, bankCard, bankZone, regionLv1, regionLv2, regionLv3, regionLv4)
                {
                    IsDefault = true
                };
            DbProvider.Add(bank);
            DbProvider.SaveChanges();
            return bank;
        }

        /// <summary>
        /// 获取用户绑定银行
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        public ICollection<UserBank> GetUserBank(int userId)
        {
            return DbProvider.D<UserBank>().Where(x => x.UserId == userId && x.IsEffect).ToList();
        }

        public UserBank GetUserBankById(int id)
        {
            return DbProvider.GetByID<UserBank>(id);
        }
    }
}
